package app

import (
	"embed"
	"fmt"
	"os/exec"
	"runtime"
	"sc_eac_passer/internal/patch"
	"time"

	"gitee.com/StarCitizen_CN/logger"
	"gitee.com/StarCitizen_CN/stargox/pkg/core"
)

// 启动游戏
func StartGame(inArgs []string) {
	start := time.Now()
	logger.Var("args == %s", inArgs)

	var newArgs []string
	newArgs = append(newArgs, inArgs[1:]...)

	launcherArgs := fmt.Sprint(newArgs)
	logger.Var("launcherArgs:\n%s\n ", launcherArgs)

	// 询问启动方式
	var targetEXE = gameEXEPath

	// todo: 使用欢迎界面而不是对话框
	title := "欢迎使用星际公民汉化工具 " + core.GitVersion
	msg := "本程序将会为星际公民启用汉化，请勿将其用作其他用途。\n" +
		"本程序由星际公民盒子开发组提供支持，反馈群：940696487\n" +
		"点击【是】开始启动星际公民。"

	if !AltertDialogWithYesNo(title, msg) {
		return
	}

	// if AltertDialogWithYesNo(title, msg) {
	// if fileExists(dbHelpDLLBackPath) {
	// 	fileRename(dbHelpDLLBackPath, dbHelpDLLPath)
	// }
	// } else {
	// targetEXE = gameEACLauncherPath
	// if !fileExists(gameEACLauncherPath) {
	// 	ShowError("请将 EAC 启动器命名为 StarCitizen_Launcher_EAC.exe 以加载原版游戏，若文件丢失，请尝试重新通过 RSI Launcher 获取。")
	// 	return
	// }
	// if fileExists(dbHelpDLLPath) {
	// 	fileRename(dbHelpDLLPath, dbHelpDLLBackPath)
	// }
	// }

	Notification("正在启动游戏", "随时为你护航")
	clean()
	runtime.GC()

	{
		out, gameExecErr := exec.Command(targetEXE, newArgs...).Output()
		if gameExecErr != nil {
			msg, url, isOpenLogFileRequired := CrashWorkaround(gameExecErr, "Game.log")

			// 暂且通过时长来区分游戏异常状态
			if time.Since(start) > time.Minute {
				ErrAlertAndJumpUrl(gameExecErr, url, "发现游戏异常退出或崩溃！", msg)
			} else {
				ErrAlertAndJumpUrl(gameExecErr, url, "游戏启动失败", msg)
			}

			if isOpenLogFileRequired {
				if gameLogSelectErr := exec.Command(`explorer`, `/select,`, `Game.log`).Start(); gameLogSelectErr != nil {
					logger.Err(gameLogSelectErr)
				}
			}
		}

		logger.Var(string(out))
	}
}

func clean() {
	patch.Patch = embed.FS{}
}
